package com.cmw.udp.l301;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPSearcher {
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("UDPSearcher Started.");
        DatagramSocket ds = new DatagramSocket();

        String requestData = "HelloWord!";
        byte[] buf = requestData.getBytes();
        DatagramPacket requestPack = new DatagramPacket(buf,buf.length);
        requestPack.setAddress(InetAddress.getLocalHost());
        requestPack.setPort(20000);
        ds.send(requestPack);

        byte[] receiveBuf = new byte[512];
        DatagramPacket receivePack = new DatagramPacket(receiveBuf, receiveBuf.length);
        ds.receive(receivePack);    //接收

        String ip = receivePack.getAddress().getHostAddress();
        int port = receivePack.getPort();
        int dataLen = receivePack.getLength();
        String data = new String(receivePack.getData());
        System.out.println(String.format("UDPSearcher receive from ip:%s\t port:%d\t data:%s\t dataLen:%d",ip, port, data, dataLen));
        System.out.println("UDPSearcher requestData send Finished!");
        ds.close();
    }
}
